#include "tcp.h"

void Server(int sockfd)
{
    while (true)
    {
        std::string message;
        std::getline(std::cin, message);
        int size = message.size();
        write(sockfd, message.c_str(), message.size());
    }

    /*while(true)
    {
        char message[20];
        read(sockfd,message,20);
        printf("%s\n",message);
    }*/
    /*while (true)
    {
        // 读取数据
        char buffer[80];
        read(sockfd, buffer, sizeof buffer);
        std::string c_message = buffer;

        // 反序列化
        Json::Value root1;
        Json::Reader reader;
        bool res = reader.parse(buffer, root1);
        int x = root1["x"].asInt();
        int y = root1["y"].asInt();
        char oper = root1["oper"].asInt();

        // 计算
        int result;
        if (y == 0 && oper == '/')
        {
            lg(INFO, "divide zero");
            result = 0;
            goto send;
        }
        switch (oper)
        {
        case '+':
            result = x + y;
            break;
        case '-':
            result = x - y;
            break;
        case '*':
            result = x * y;
            break;
        case '/':
            result = x / y;
            break;
        default:
            lg(INFO, "illegal operators");
            exit(2);
            break;
        }
        send:
        // 序列化
        Json::Value root2;
        root2["result"] = result;
        Json::FastWriter writer;
        std::string s = writer.write(root2);
        lg(DEBUG, "result: %s", s.c_str());
        // 发送数据
        ssize_t w = write(sockfd, s.c_str(), s.size());
        if (w < 0)
        {
            lg(FATAL, "write fail");
        }
    }*/
}

int main()
{
    // 创建套接字
    int listensocket = socket(AF_INET, SOCK_STREAM, 0);
    if (listensocket < 0)
    {
        lg(FATAL, "socket fial!!!");
        return 0;
    }
    lg(DEBUG, "socket success");

    // 绑定套接字
    struct sockaddr_in local;
    memset(&local, 0, sizeof local);
    local.sin_addr.s_addr = INADDR_ANY;
    local.sin_port = htons(8888);
    local.sin_family = AF_INET;
    int b = bind(listensocket, (struct sockaddr *)&local, sizeof local);
    if (b < 0)
    {
        lg(FATAL, "bind fail!!!");
        return 0;
    }
    lg(DEBUG, "bind success");

    // 将套接字设置为listen状态
    int l = listen(listensocket, 8);
    if (l < 0)
    {
        lg(FATAL, "listen fail!!!");
        return 0;
    }
    lg(DEBUG, "listen success");

    // 获取新连接
    struct sockaddr_in client;
    memset(&client, 0, sizeof client);
    socklen_t len = sizeof client;
    int sockfd = accept(listensocket, (struct sockaddr *)&client, &len);
    lg(INFO, "accept sucess,IP: %s, Port: %d", inet_ntoa(client.sin_addr), client.sin_port);
    Server(sockfd); // 提供给客户端的服务
    return 0;
}
